<?php

class PushController
{
    private $jpushSetModel;
    private $autoUidModel;
    private $actions;
    private $tokenUserCacheModel;
    public  $diaryListCacheModel;
    private $userStatisticsModel;
    private $baidu_key_ios_2;
    private $baidu_secretKey_ios_2;

    function __construct()/*{{{*/
    {
        $this->jpushSetModel        =   new JpushSetModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->tokenUserCacheModel  =   new TokenUserCacheModel();
        $this->diaryListCacheModel  =	new DiaryListCacheModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->baidu_key_ios_2      =   '55eRZyxQ1uNpMbt9ydU1SxZS';
        $this->baidu_secretKey_ios_2=   'Yr9GB28CEf54m05z1369Yp9nT5A3WmH2';
        $this->actions 			 	=   array('addJpush','setPush','getPushInfo',
        									'checkPushSet','setStop','setPushTag',
        								);
    }/*}}}*/
    
    public function callApi($param)/*{{{*/
    {
    	$ac = $param['action'];
    	# check $do /*{{{*/
    	$doCheck    =   $this->checkAction($ac);
    	if (!empty(AC::$errorNo))
    	{
    		return  $doCheck;
    	} /*}}}*/
    
    	return $this->$ac($param);
    }/*}}}*/
    
    /**
     * 添加推送自定义设置
     * @param array $info
     * @return boolean
     */
    public function addJpush($info)/*{{{*/
    {
    	$result = $this->jpushSetModel->addJpush($info);
    	return $result;
    }/*}}}*/
    
    /**
     * 获取自定义的推送设置详情
     * @param array $info
     * @return boolean|Ambigous <boolean, multitype:, unknown>
     */
    public function getPushInfo($info)/*{{{*/
    {
        // 绑定
    	$result     =   $this->jpushSetModel->getPushInfo($info);
    	if ($result)
    	{
    		$result['jpush_extra'] = json_decode($result['jpush_extra'],true);
    	}else{
    		$result['uid'] 		= $info['uid'];
    	}
    	
        $data = $this->pushInfoData($result);
        $push = array();
        $push['push_info'] = $data;
        return $push;
    }/*}}}*/
    
    private function pushInfoData($info)/*{{{*/
    {
    	$data = array();
    	$data['uid'] 		       = $info['uid'];
    	isset($info['deviceSN'])       ? $data['deviceSN']    	= $info['deviceSN'] 		: '';
    	isset($info['master_control']) ? $data['control']    	= $info['master_control'] 	: '0';
    	isset($info['dnd_set'])        ? $data['disturb']    	= $info['dnd_set'] 		: '0';
    	isset($info['sound_show'])     ? $data['sound_show'] 	= $info['sound_show'] 		: '0';
    	isset($info['content_show'])   ? $data['content_show'] 	= $info['content_show'] 	: '0';
    	isset($info['commentPush'])    ? $data['commentPush'] 	= $info['commentPush'] 		: '0';
    	isset($info['messagePush'])    ? $data['messagePush'] 	= $info['messagePush'] 		: '0';
    	isset($info['followPush'])     ? $data['followPush'] 	= $info['followPush'] 		: '0';
    	isset($info['startHour'])      ? $data['startHour'] 	= $info['startHour'] 		: AC::START_HOUR;
    	isset($info['endHour'])        ? $data['endHour'] 	= $info['endHour'] 		: AC::END_HOUR;
    	$data['extra'] = (Object) array();
    	isset($info['jpush_extra'])    &&    $data['extra']    =    $info['jpush_extra'];
    	return $data;
    }
    
    /**
     * 是否关闭推送
     * @param unknown $info
     * @return boolean
     */
    public function setStop($info)/*{{{*/
    {
    	$result = $this->jpushSetModel->setStop($info);
    	return $result;
    }/*}}}*/
    
    /**
     * 相应模块推送的关闭
     * @param unknown $info
     * @return Ambigous <boolean, unknown>
     */
    public function setPushTag($info)/*{{{*/
    {
    	$push = $this->getPushInfo(array('uid'=>$info['uid']));
    	if ($push['control'] != 0)
    	{
    		AC::$errorNo = 'JPUSH008';
    		return false;
    	}
    	$result = $this->jpushSetModel->setPushTag($info);
    	return $result;
    }/*}}}*/

    /**
     * 编辑推送自定义的设置
     * @param array $info
     * @return boolean
     */
    public function setPush($info)/*{{{*/
    {
    	$push     =   $this->jpushSetModel->getPushInfo(array('uid'=>$info['uid']));
    	if ($push['master_control'] != 0)
    	{
    		return false;
    	}
    	if(isset($info['extra'])){
    	    $urlarr = parse_url($info['extra']);
    	    $data   = $parr = array();
    	    parse_str($urlarr['path'],$parr);
    	    $extra = json_decode($push['jpush_extra'],true);
    	    $extra['baidu_push_info'] = $parr;
    	    $info['jpush_extra'] = json_encode($extra);
    	}
    	if (isset($info['tags'])){
    	    if (!is_array($info['tags'])){
    	        $info['tags'] = array();
    	    }
    	    $extra = json_decode($push['jpush_extra'],true);
    	    $extra['tags'] = $info['tags'];
    	    $info['jpush_extra'] = json_encode($extra);
    	} 
    	$result = $this->jpushSetModel->setPush($info);
    	return $result;
    }/*}}}*/
    
    /**
     * 检测推送设置
     * @param int $uid
     * @param int $type
     * @return boolean
     */
    public function checkPushSet($uid,$type)/*{{{*/
    {
    	$result 	= 	$this->jpushSetModel->getPushInfo(array('uid'=>$uid));
    	
    	# 开关
    	if ($result['master_control']   != 0 ) return false;
    	if (empty($result['deviceSN'])) return false;
    	
    	$time		=	intval(date("H",AC::SERVER_TIME));
    	if ($result['disturb'] == 0 && $result['startHour'] > $result['endHour'])
    	{
    		if (($time >= $result['startHour'] && $time < 24) || ($time >= 0 && $time < $result['endHour'])) return false;
    	}
    	if ($result['disturb'] == 0 && $result['startHour'] < $result['endHour'])
    	{
    		if ($time >= $result['startHour'] && $time < $result['endHour']) return false;
    	}
    	
    	if ($result['messagePush'] 		!= 0 && $type == 1) 	return false;
    	if ($result['followPush']  		!= 0 && $type == 2) 	return false;
    	if ($result['commentPush'] 		!= 0 && $type == 4) 	return false;
    	return $result;
    }
    
	/**
	 * 推送
	 * @param unknown $info 详情
	 * @param unknown $action 推送类型(日记评论、私信、关注/话题评论)
	 * @return boolean
	 */
	public function push($info, $action)/*{{{*/
	{
		$actions    =   array(
				"pushMessage"	=>	array(
									'uid'	=>	$info['mUid'],
									'push_type'	=>	1,
									'count'		=>	'messageTimes',
									'action'	=>	'message'
								),
				"pushFollow"	=>	array(
									'uid'	=>	$info['fUid'],
									'push_type'	=>	2,
									'count'		=>	'newFollowTimes',
									'action'	=>	'follow'
								),
				"pushComment"	=>	array(
									'uid'	=>	isset($info['parentId']) && intval($info['parentId'])>0 ? $info['rUid'] : $info['cUid'],
									'push_type'	=>	4,
								    'count'		=>	"newCommentTimes",
									'action'	=>	'comment'
								),
				"pushTopicComment"	=>	array(
									'uid'	=>	isset($info['parentId']) && intval($info['parentId'])>0 ? $info['rUid'] : $info['author_uid'],
									'push_type'	=>	4,
									'count'		=>	"newTopicComment",
									'action'	=>	'topicComment'
								)
		);
		
		// 不对用户自己推送
		if (AC::HOST_UID == $actions[$action]['uid']){
		    return TRUE;
		}
		
		// 屏蔽私信推送
		if (AC::$closeBdMsgpushVersion && ($action == "pushMessage")) {
		    return true;
		}
		
		$check		=	$this->checkPushSet($actions[$action]['uid'], $actions[$action]['push_type']);
		if (!$check) return true;
		
		// 判断IOS还是安卓
		$extra     = json_decode($check['jpush_extra'],true);
		list($OS, $platform)     = UK::getOsAndPlantform($extra);
		
		// 获取轮询数字
		$statics    =   $this->userStatisticsModel->getUserStatistics(array('uid'=>$actions[$action]['uid']));
		$info[$actions[$action]['count']] = $statics[$actions[$action]['count']];
		
		// 结构化数据
		$ac = $actions[$action]['action'].'PushData';
		$formatData = $this->$ac($info, $OS, $check['content_show']);
		if (!empty($formatData['content'])){
		    $formatData['content'] = Emotion::emotionToCharacter($formatData['content']);
		}
		
		// 设备号截取前5位
		$deviceSN   = substr($check['deviceSN'],0,5);

		if ($extra && !empty($extra['baidu_push_info']['baidu_user_id'])){
		    if ($OS == 1){
		        Jpush::baiduPushAnd($formatData, $extra['baidu_push_info']['baidu_user_id'], $deviceSN);
		    }else{
		        Jpush::baiduPushIos($formatData, $extra['baidu_push_info']['baidu_user_id'], $deviceSN, $this->baidu_key_ios_2, $this->baidu_secretKey_ios_2, $platform);
		    }
		}
        
		return TRUE;
	}
	
	/**
	 * 群组推送
	 * @param unknown $info
	 * @param unknown $action
	 */
	public function tagPush($info, $action){
	    if (AC::$closeBdMsgpushVersion) {
	        return true;
	    }
	    
	    $data = array(
	            'content'  =>    $info['content'],
	            'extras'   =>    array(
	                    'uid'      =>  $info['uid'],
	                    'nickname' =>  $info['nickname'],
	                    'gid'      =>  $info['gid'], 
	                    'name'     =>  $info['name'],
	                    'type'     =>  6,
	                    'time'     =>  AC::SERVER_TIME, 
	            )
	    );
	    
	    $data['content'] = Emotion::emotionToCharacter($data['content']);
	    Jpush::baiduTagPush($data, $this->baidu_key_ios_2, $this->baidu_secretKey_ios_2);
	}
	
	private function messagePushData($info, $device, $content)/*{{{*/
	{
		// 获取备注名
		$uid = $info['mUid'];
		$nickname = $this->autoUidModel->getRemarkName(array('uid'=>$info['uid'],'nickname'=>$info['nickname']),$uid);
		$eventTypeGid = 0;
		
		
		$data['content'] = $info['content'];
		$data['data'] 	 = array(
				'uid' 	 	=>  $uid,
				'nickname'	=>	$info['mNickname'],
				'fromUid'	=>	$info['uid'],
				'fNickname'	=>	$nickname,
				'time'		=>	AC::SERVER_TIME,
				'type'		=>	1,
				'eventType' 	=>  	$info['eventType'],
				'eventTypeGid'  =>  	$info['eventTypeGid'],
				'messageTimes'	=>	$info['messageTimes']
		);
		
		// IOS通知内容
		if ($device != 1){
			$data['content']	=	$nickname.':'.$info['content'];
			if ($content !=0){
				$data['content'] = "你收到了一条私信";
			}
		}
		
		return $data;
	}/*}}}*/
	
	private function followPushData($info, $device, $content)/*{{{*/
	{
		// 获取备注名
		$uid = $info['fUid'];
		$nickname = $this->autoUidModel->getRemarkName(array('uid'=>$info['uid'],'nickname'=>$info['nickname']),$uid);
		
		$data['content'] = $nickname.'关注了你';
		$data['data'] 	 = array(
				'uid' 	 	=>  $uid,
				'nickname'	=>	$info['fNickname'],
				'fromUid'	=>	$info['uid'],
				'fNickname'	=>	$nickname,
				'time'		=>	AC::SERVER_TIME,
				'type'		=>	2,
				'newFollowTimes'	=>	$info['newFollowTimes']
		);
		
		// IOS屏蔽通知内容时的格式
		if ($content !=0 && $device != 1){
			$data['content'] = "有人关注了你";
		}
		return $data;
	}/*}}}*/
	
	private function commentPushData($info, $device, $content)/*{{{*/
	{
		// 获取备注名
		$uid = isset($info['parentId']) && intval($info['parentId']) > 0 ? $info['rUid'] : $info['cUid'];
		$nickname = $this->autoUidModel->getRemarkName(array('uid'=>$info['uid'],'nickname'=>$info['nickname']),$uid);
		
		$data['content'] = $info['content'];
		$data['data'] 	 = array(
				'uid'		=>	$uid,
				'nickname'	=>	$info['cNickname'],
				'fromUid'	=>	$info['uid'],
				'fNickname'	=>	$nickname,
				'bodyId'	=>	$info['bodyId'],
				'time'		=>	AC::SERVER_TIME,
				'type'		=>	4,
				'newCommentTimes'	=>	$info['newCommentTimes']
		);
		
		// IOS通知内容
		if ($device != 1){
			if($info['parentId']>0){
				$data['content'] = $nickname.'回复了你:'.$info['content'];
			}else{
				$data['content'] = $nickname.'评论了你的点滴:'.$info['content'];
			}
			if ($content !=0){
				$data['content'] = "有人评论了你的点滴";
			}
		}
		
		return $data;
	}/*}}}*/
	
	private function topicCommentPushData($info, $device, $content)/*{{{*/
	{
		// 获取备注名
		$uid = isset($info['parentId']) && intval($info['parentId']) > 0 ? $info['rUid'] : $info['author_uid'];
		$nickname = $this->autoUidModel->getRemarkName(array('uid'=>$info['uid'],'nickname'=>$info['nickname']),$uid);
		
		$data['content'] = $info['content'];
		$data['data'] 	 = array(
				'uid'		=>	$uid,
				'nickname'	=>	$info['author_name'],
				'fromUid'	=>	$info['uid'],
				'fNickname'	=>	$nickname,
				'tid'		=>	$info['tid'],
				'time'		=>	AC::SERVER_TIME,
				'type'		=>	5,
				'newTopicComment'	=>	$info['newTopicComment']
		);
		
		// IOS通知内容
		if ($device != 1){
			$data['content'] = $nickname.'在粉粉圈中评论了你:'.$info['content'];
			if ($content !=0 ){
				$data['content'] = "有人在粉粉圈中评论了你";
			}
		}

		return $data;
	}/*}}}*/
	
    private function checkAction($action)/*{{{*/
    {
    	if (in_array($action, $this->actions) && method_exists($this, $action))  return  TRUE;
    	AC::$errorNo    =   'SA004';
    	return  ' Error : call do is not exists in PushController! ';
    }/*}}}*/
   
}